<template>
	<view class="wrap">
		<scroll-view 
			scroll-y="true" 
			@scrolltolower="loadMore"
			style="height: 93vh;"
		>
			<view class="news-list-section">
				<view v-for="(item, idx) in showList" :key="idx">
					<div style="width: 100%;">
						<view class="news-item" @click="navToForm(item)">
							<text class="news-title">{{item.title}}</text>
							<view class="news-meta">
								<text class="news-source">{{item.source}}</text>
								<text class="news-date">{{item.date}}</text>
								<button style="border: none !important;" class="detail-button blue-text">详情</button>
							</view>
						</view>
					</div>
				</view>
			</view>
			
			<!-- 加载状态显示 -->
			<view class="loading-container" v-if="loading">
				<u-loading mode="spinner" size="28"></u-loading>
				<text class="loading-text">加载中...</text>
			</view>
			
			<!-- 没有更多数据提示 -->
			<view class="no-more-container" v-if="finished && showList.length > 0">
				<u-divider text="没有更多数据了"></u-divider>
			</view>
			
			<!-- 空状态 -->
			<view class="empty-container" v-if="!loading && showList.length === 0">
				<u-empty text="暂无数据" mode="data"></u-empty>
			</view>
		</scroll-view>

		<!-- 文件列表弹窗 -->
		<view v-if="showFileListDialog" class="file-list-dialog-overlay" @click.self="showFileListDialog = false">
			<view class="file-list-dialog-content">
				<view class="dialog-title">请选择文件</view>
				<scroll-view scroll-y class="file-list-scroll">
					<view class="file-item" v-for="(file, fileIdx) in currentFileList" :key="fileIdx"
						@click="openFilePreview(file)">
						<text class="file-name">{{ file.fileName }}</text>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>
<script>
	/**
	 * Copyright (c) 2013-Now http://aidex.vip All rights reserved.
	 */
	import {
		checkLogin
	} from '@/common/auth.js';
	import config from '@/common/config.js';
	export default {
		data() {
			return {
				keywords: '',
				showList: [], // Current displayed data
				pageNo: 1,
				pageSize: 10,
				loading: false,
				finished: false,
				categoryId: '',
				categoryName: '',
				position: '',
				showFileListDialog: false, // Control file list dialog visibility
				currentFileList: [] // Stores files for the current item
			};
		},
		onLoad(options) {
			if (!checkLogin()) {
				return;
			}
			if (options.categoryId) {
				this.categoryId = options.categoryId;
			}
			if (options.categoryName) {
				this.categoryName = options.categoryName;
				uni.setNavigationBarTitle({
					title: this.categoryName
				});
			}
			if (options.position) {
				this.position = options.position;
			}
			this.loadData();
		},
		methods: {
			search() {
				this.pageNo = 1;
				this.showList = [];
				this.finished = false;
				this.loadData();
			},
			navToForm(item) {
				if (item.channelType === 'file') {
					if (item.fileUrlList && item.fileUrlList.length > 0) {
						if (item.fileUrlList.length > 1) {
							this.currentFileList = item.fileUrlList;
							this.showFileListDialog = true;
						} else {
							this.openFilePreview(item.fileUrlList[0], item.title);
						}
					} else {
						uni.showToast({
							title: '没有找到可预览的文件',
							icon: 'none'
						});
					}
				} else {
					uni.navigateTo({
						url: `/pages/sys/new/form?id=${encodeURIComponent(item.id)}`
					});
				}
			},
			openFilePreview(file, defaultTitle = '') {
				const timestamp = new Date().getTime();
				const encodedUrl = encodeURIComponent(config.importantBaseUrl  + file.fileUrl);
				console.log(encodedUrl)
				const url = `https://xdoc.sdhwj.com/view?mtime=${timestamp}&src=${encodedUrl}`;
				console.log(url)
				window.open(url, '_blank');
				this.showFileListDialog = false; // Close dialog after opening file
			},
			async loadData() {
				if (this.loading || this.finished || !this.position) {
					console.log('loadData blocked:', { loading: this.loading, finished: this.finished, position: this.position });
					return;
				}

				console.log('loadData started, pageNo:', this.pageNo);
				this.loading = true;
				try {
					// 栏目名称与cateCodes映射
					const cateCodeMap = {
						'图片新闻': '8ae8c1836a7217f8016a734789c80003',
						'时政信息': '8ae8c18369f4fe350169f67c618f0002',
						'部委信息': '8ae8c18369f4fe350169f67c26730001',
						'重要信息': '8ae8c18369f4fe350169f67bdb6f0000',
						'媒体聚焦': '8ae8c1fd47cf621f0147dcf84b9b010b',
						'重要通知': 'C20',
						'公示公告': 'C21',
						'人事任免': '8ae8c1834b489b6c014b7b6987081192',
						'廉政天地': '8ae8c1fd480b26770148156da05f0de8',
						'三风共建': '8ae8c183788567ee017886f2df3c2483',
						'领导讲话': 'C23',
						'政务信息': 'C24',
						'防汛动态': 'F4',
						'每周要情': 'C25',
						'防汛例会纪要':'A2',
						// '会议纪要': 'C26',
						'部门动态': 'A2A',
						'市局动态': '8ae8c1fd47cf621f0147dd1e2a2c011f002',
						'局直动态': '8ae8c1fd47cf621f0147dd1e2a2c011f001',
						'督查通报': '8ae8c4e0482b52cc01482b68a8460000',
						'有为机关': '8ae8c183785c727201785e08e6400132',
						'局领导工作安排':'C22',
						'会议纪要':'B16,B18'
					};
					const cateCodes = cateCodeMap[this.categoryName] || '';
					const params = {
						...{
							siteCode: 'main',
							position: this.position,
							__ajax: 'json',
							pageNo: this.pageNo,
							pageSize: this.pageSize,
							'__sid': uni.getStorageSync('sessionid'),
							'x-remember': uni.getStorageSync('x-remember'),
							title: this.keywords
						},
						type: 1,
						cateCodes
					};
					
					let isOldApi = (this.categoryName === '近日发文' || this.categoryName === '近日收文');
					let response;
					if (isOldApi) {
						response = await this.$u.api.getArticleListOld(params);
					} else {
						response = await this.$u.api.getArticleList(params);
					}
					
					const result = response.resultEntity || response;
					if (result.code === 1 && result.data && result.data.list) {
						let processedList;
						if (isOldApi) {
							processedList = result.data.list.map(article => ({
								id: (article.fileUrlList && article.fileUrlList[0] && article.fileUrlList[0].id) || '',
								title: article.contentTitle,
								source: article.channelName,
								date: article.onlineDate,
								channelType: article.channelType,
								fileUrlList: article.fileUrlList || []
							}));
						} else {
							processedList = result.data.list.map(article => ({
								id: article.id,
								title: article.title,
								source: article.category && article.category.categoryName ? article.category.categoryName : '',
								date: article.onlineDate,
								webUrl: article.url,
								image: article.image || ''
							}));
						}
						
						this.showList = this.showList.concat(processedList);
						this.finished = (result.data.list.length < this.pageSize);
						console.log('Data loaded:', { 
							newItems: processedList.length, 
							totalItems: this.showList.length, 
							finished: this.finished,
							pageNo: this.pageNo 
						});
					} else {
						this.finished = true;
					}
				} catch (error) {
					console.error('获取文章列表失败:', error);
					uni.showToast({
						title: '获取文章列表失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			loadMore() {
				// 分页加载更多
				console.log('loadMore triggered!', this.pageNo, this.loading, this.finished);
				this.pageNo++;
				this.loadData();
			}
		}
	};
</script>
<style lang="scss">
	@import '../../../common/uni.css';

	page {
		height: 100%;
		background-color: #f2f2f2;
	}

	.wrap {
		display: flex;
		flex-direction: column;
	}

	.container {
		padding: 20rpx;
	}

	.wrap .search {
		background: #ffffff;
	}

	.msg-time {
		font-size: 26rpx;
		padding: 10px 0;
		color: #999999;
		text-align: center;
	}

	.scroll-list {
		flex: 1;
		min-height: 0;
		/* Critical for scrollable flex item */
		// padding-bottom: 150rpx; /* Ensure u-loadmore is visible */
	}

	.msg-list-item {
		/* No specific height or overflow here, scroll-y="true" handles it */
	}

	.u-card__foot {
		.u-icon {
			margin-right: 10px;
		}
	}

	.news-list-section {
		// background-color: white;
		border-radius: 15rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		margin-top: 0;
		margin-bottom: 0;
	}

	.news-item {
		background-color: white;
		padding: 30rpx;
		border-bottom: 1rpx dashed #eee;
		margin-bottom: 10rpx;

		&:last-child {
			border-bottom: none;
		}

		.news-title {
			font-size: 30rpx;
			color: #000000;
			line-height: 1.4;
			margin-bottom: 10rpx;
		}

		.news-meta {
			margin-top: 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 24rpx;
			color: #555555;

			.news-source {
				width: 33.33%;
				margin-right: 20rpx;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				flex-shrink: 1;
				flex-grow: 0;
			}

			.news-date {
				// width: 35%;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				flex-shrink: 1;
				flex-grow: 0;
				text-align: center;
			}

			.detail-button {
				float: right;
				width: 15%;
				background-color: rgba(0, 157, 240, 0.11);
				color: #009DFF;
				border: none !important;
				padding: 8rpx 0rpx;
				font-size: 24rpx;
				margin-right: 0rpx;
				min-width: unset;
				height: unset;
				line-height: unset;
				flex-shrink: 0;
			}

			.uni-button:after {
				border: none !important;
			}

			.detail-button:after {
				border: none !important;
			}
		}
	}

	/* File list dialog styles */
	.file-list-dialog-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 1000;
	}

	.file-list-dialog-content {
		background-color: #fff;
		border-radius: 16rpx;
		width: 80%;
		max-height: 70%;
		display: flex;
		flex-direction: column;
		padding: 30rpx;
	}

	.dialog-title {
		font-size: 34rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		text-align: center;
		color: #333;
	}

	.file-list-scroll {
		flex: 1;
		max-height: 600rpx;
		/* Limit scroll height */
		margin-bottom: 20rpx;
	}

	.file-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
		font-size: 30rpx;
		color: #333;
	}

	.file-item:last-child {
		border-bottom: none;
	}

	.file-name {
		flex: 1;
		margin-right: 20rpx;
		white-space: normal;
		overflow: visible;
		text-overflow: clip;
		word-break: break-all;
	}

	.file-arrow {
		color: #999;
		font-weight: bold;
	}

	.close-button {
		background-color: #007AFF;
		color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		font-size: 32rpx;
		text-align: center;
		margin-top: 20rpx;
	}

	/* Loading container styles */
	.loading-container {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 40rpx 20rpx;
		background-color: #f8f8f8;
		border-radius: 10rpx;
		margin: 20rpx;
	}

	.loading-text {
		margin-left: 20rpx;
		font-size: 28rpx;
		color: #666;
	}

	/* No more data container styles */
	.no-more-container {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 30rpx 20rpx;
		margin: 20rpx;
	}

	/* Empty container styles */
	.empty-container {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 100rpx 20rpx;
		margin: 20rpx;
		background-color: #f8f8f8;
		border-radius: 10rpx;
	}
</style>